var orderEditAction = {
    init: function() {
        console.log('orderEdit init');
        var that = this;
        this.orderAddView = $("#orderAddView");
        if (this.orderAddView.hasClass('inited')) {
            this.refresh();
            return;
        }
        this.orderAddView.addClass('inited');
        console.log('orderAdd init');

        this.managerGoods();
        this.delGoods();

        
        this.selectPopup({
            title:"选择车辆类型",
            url:'/carType/list',
            inputId :'#carTypeSelect',
            radioName:"selectCartype",
            valField:"carTypeId",
            txtField:"carTypeName"
        });

        // 装货
        this.selectPopup({
            title:"选择装货地企业",
            url:'/address/list',
            inputId :'#shipAddrCompanySelect',
            radioName:"selectShipAddrCompany",
            valField:"endCompany",
            txtField:"endCompany",
            params:{
                addressType : 1
            },
            dynamicParams:{
                searchStr:function(){
                    return $("#shipAddrSelect").attr('m-value');
                }
            },
            before:function(){
                var shipAddrSelect = $("#shipAddrSelect").attr('m-value');
                if(shipAddrSelect){
                    return true;
                }else{
                    F7.alert('请先选择装货地址');
                    return false;
                }
            }
        });

        this.selectPopup({
            title:"选择联系人",
            url:'/address/list',
            inputId :'#shipAddrContactSelect',
            radioName:"shipAddrContact",
            valField:"userName",
            txtField:"userName",
            params:{
                addressType : 1,
                searchStr:''
            },
            before:function(){
                var shipAddrCompany = $("[name='shipAddrCompany']").val();
                if(shipAddrCompany){
                    return true;
                }else{
                    F7.alert('请先选择装货地企业');
                    return false;
                }
            }
        });

        this.selectArea({
            el:'#shipAddrSelect',
            provinceName:'shipAddrProvince',
            cityName:'shipAddrCity',
            districtName:'shipAddrDistrict'
        });

        // 卸货
        this.selectPopup({
            title:"选择卸货地企业",
            url:'/address/list',
            inputId :'#unShipAddrCompanySelect',
            radioName:"selectUnShipAddrCompany",
            valField:"company",
            txtField:"company",
            params:{
                addressType : 0,
                searchStr:''
            }
        });

        this.selectPopup({
            title:"选择联系人",
            url:'/address/list',
            inputId :'#unShipAddrContactSelect',
            radioName:"shipAddrContact",
            valField:"userName",
            txtField:"userName",
            params:{
                addressType : 0,
                searchStr:''
            }
        });

        this.selectArea({
            el:'#unShipAddrSelect',
            provinceName:'unShipAddrProvince',
            cityName:'unShipAddrCity',
            districtName:'unShipAddrDistrict'
        });

        // 承运方
        this.selectPopup({
            title:"选择承运方企业",
            url:'/companyFollow/list',
            inputId :'#carrierSelect',
            radioName:"selectCarrier",
            valField:["companyFollow","companyId"],
            txtField:["companyFollow","companyName"]
        });

        this.selectPopup({
            title:"选择接收人",
            url:'/user/query4AutoComplete',
            inputId :'#carrierContactSelect',
            radioName:"selectCarrierContact",
            valField:"userId",
            txtField:"realName",
            params:{
                isDriver : 2
            },
            before:function(){
                var carrierCompanyName = $("#carrierCompanyName").val();
                if(carrierCompanyName){
                    return true;
                }else{
                    F7.alert('请先选择承运方企业');
                    return false;
                }
            },
            dynamicParams:{
                companyId:function(){
                    return $("#carrierCompanyName").val();
                }
            },
            afterChange:function(data){
                var carrierContactId = $(this).val();
                for (var i = 0; i < data.length; i++) {
                    if(data[i].userId == carrierContactId){
                        $("[name='carrierPhone']").val(data[i].userPhone);
                        return;
                    }
                }
            }
        });

        // 商品选择
        /*this.selectPopup({
            title:"选择商品",
            url:'/companyFollow/list',
            inputId :'#carrierSelect',
            radioName:"selectCarrier",
            valField:["companyFollow","companyId"],
            txtField:["companyFollow","companyName"]
        });*/

        this.orderAddView.on('focus','input',function(){
            F7.hideToolbar(".tabbar");
        });

        this.orderAddView.on('blur','input',function(){
            F7.showToolbar(".tabbar");
        });
        

        this.formSubmit();
    },
    refresh:function(){

    },
    delGoods:function(){
        $("#orderGoodsListRender").on('click','.order-edit-good-item-del',function(){
            var self = $(this);
            self.parents('.order-edit-good-item').remove(0);
        });
    },
    selectPopup: function(params) {
        var that = this;
        var popupTitle = params.title ? params.title:'请选择';

        var popupHTML = ['<div class="popup select-popup">',
            '<div class="view navbar-fixed">',
            '<div class="pages">',
            '<div data-page="autoComplete-cartype" class="page autocomplete-page">',
            '<div class="navbar no-border">',
            '<div class="navbar-inner">',
            '<div class="left sliding"><a href="#" class="link close-popup"><i class="icon icon-back"></i><span>关闭</span></a></div>',
            '<div class="center sliding">'+popupTitle+'</div>',
            '</div>',
            '</div>',
            '<form data-search-list=".list-block-search" data-search-in=".item-title" class="searchbar searchbar-init">',
                '<div class="searchbar-input">',
                  '<input type="search" placeholder="输入关键字搜索"><a href="#" class="searchbar-clear"></a>',
                '</div><a href="#" class="searchbar-cancel">取消</a>',
            '</form>',
            '<div class="searchbar-overlay"></div>',
            '<div class="page-content">',
                '<div class="content-block searchbar-not-found">',
                    '<div class="content-block-inner">暂无数据</div>',
                '</div>',
                '<div class="list-block list-block-search searchbar-found"><ul id="popupSelect">',
                '</ul></div>',
            '</div>',
            '</div>',
            '</div>',
            '</div>',
            '</div>'
        ].join('');

        $(params.inputId).on('click', function() {
            var self = $(this);

            if(typeof params.before === "function"){
                if(!params.before()){
                    return false;
                }
            }

            F7.popup(popupHTML);
            F7.showIndicator();
            var setList = function(data){
                var listHtml='';
                for (var i = 0; i < data.length; i++) {
                    var inputVal =typeof params.valField === "object" ? data[i][params.valField[0]][params.valField[1]]:data[i][params.valField];
                    var selectStatus = self.next('input').val() == inputVal ? ' checked="checked"':'';
                    var txtField = typeof params.txtField === "object" ? data[i][params.txtField[0]][params.txtField[1]] :data[i][params.txtField] ;

                    listHtml += ['<li>',
                          '<label class="label-radio item-content">',
                            '<input type="radio" name="'+params.radioName+'" data-txt="'+txtField+'" value="'+inputVal+'" '+selectStatus+'>',
                            '<div class="item-inner">',
                              '<div class="item-title">'+txtField+'</div>',
                            '</div>',
                          '</label>',
                        '</li>'].join('');
                }
                $("#popupSelect").html(listHtml);

                $('[name='+params.radioName+']').on('change',function(){
                    var _self = $(this);
                    self.val(_self.data('txt')).next('input').val(_self.val());
                    if(typeof params.afterChange === 'function') params.afterChange.call(this,data);
                    F7.closeModal('.select-popup');
                });
                F7.hideIndicator();
            };

            var popupAjaxParams = loginAction.loginParams();
            $.extend(popupAjaxParams, params.params||{});

            if(params.dynamicParams){
                var dynParams={};
                $.each(params.dynamicParams, function(index, val) {
                     if(typeof val === 'function') dynParams[index] = val();
                });

                $.extend(popupAjaxParams, dynParams||{});
            }

            appXhr.POST(params.url,popupAjaxParams).done(function(data) {
                // Find matched items
                if (data.code === 100) {
                    setList(data.content);
                    
                }

            });
        });
    },
    managerGoods:function(){
        $("#orderAddGoods").on('click',function(){
            app.tplManager({
                tplEl:'#orderGoodsListTpl',
                renderEl:'#orderGoodsListRender',
                isAppend: true
            });
        });
        
    },
    selectArea:function(params){
        var that =  this;
        $(params.el).on('click', function() {
            var popupHTML = ['<div class="popup area-popup">' ,
                                '<div class="view navbar-fixed">',
                                    '<div class="pages">',
                                        '<div data-page="selectArea" class="page">',
                                        '<div class="navbar no-border">',
                                        '<div class="navbar-inner">',
                                        '<div class="left"><a href="#" class="link close-popup"><i class="icon icon-back"></i><span>关闭</span></a></div>',
                                        '<div class="center">选择地址</div>',
                                        '</div>',
                                        '</div>',
                                        '<div class="page-content">',
                                            '<div m-role="cell" m-layout="fit" class="h100p" m-mode="y">',
                                                '<div m-role="cell" m-align="center" m-valign="middle" class="selected-area">',
                                                    '<div id="selectedProvince" class="margin-r-5">省</div>',
                                                    '<div class="margin-r-5">-</div>',
                                                    '<div id ="selectedCity" class="margin-r-5">市</div>',
                                                    '<div class="margin-r-5">-</div>',
                                                    '<div id="selectedDistrict" class="">区</div>',
                                                '</div>',
                                                '<div>',
                                                    '<div id="provincesSelect"></div>',
                                                    '<div id="CitySelect"></div>',
                                                    '<div id="districtsSelect"></div>',
                                                '</div>',
                                                '<div m-role="cell" m-mode="y" m-layout="fit">',
                                                    '<div class="tabs-animated-wrap h100p">',
                                                        '<div class="tabs h100p">',
                                                            '<div id="provinceList" class="tab h100p overflow-auto active">',
                                                            '</div>',
                                                            '<div id="cityList" class="tab h100p overflow-auto">',
                                                                
                                                            '</div>',
                                                            '<div id="districtList" class="tab h100p overflow-auto">',

                                                            '</div>',
                                                        '</div>',
                                                    '</div>', 
                                                '</div>',

                                                '<div m-role="cell" m-mode="y">',
                                                    '<div m-role="cell">',
                                                        '<div class="w100p buttons-row padding-t-10 padding-l-15 padding-r-15 padding-b-10">',
                                                            '<a href="#provinceList" class="tab-link active button">选择省</a>',
                                                            '<a href="#cityList" class="tab-link button">选择市</a>',
                                                            '<a href="#districtList" class="tab-link button">选择区/县</a>',
                                                        '</div>',
                                                    '</div>',
                                                    '<div m-role="cell" m-mode="x-equal" class="bg-white padding-t-10 padding-b-10">',
                                                        '<div m-role="cell" class="padding-l-15 padding-r-10">',
                                                            '<a m-role="cell" m-align="center" m-layout="fit" href="#" id="cancelSelectArea" class="button">取消</a>',
                                                        '</div>',
                                                        '<div m-role="cell" class="padding-r-15">',
                                                            '<a m-role="cell" m-align="center" m-layout="fit" href="#" id="okSelectArea" class="button button-fill">确定</a>',
                                                        '</div>',
                                                    '</div>',
                                                '</div>',
                                            '</div>',
                                        '</div>' ,
                                        '</div>' ,
                                    '</div>' ,
                                '</div>' ,
                            '</div>'].join('');
            F7.popup(popupHTML);
            that.getProvince();
            that.selectProvince(params);
            that.selectCity(params);
            that.selecDistrict(params);

            $("#cancelSelectArea").on('click',function(){
                $('[name="'+params.provinceName+'"]','[name="'+params.cityName+'"]','[name="'+params.districtName+'"]').val('');
                F7.closeModal('.area-popup');
            });

            $("#okSelectArea").on('click',function(){
                var el =$(params.el),
                    province = $("#selectedProvince").data('name'),
                    provinceId = $("#selectedProvince").data('id'),
                    city = $('#selectedCity').data('name'),
                    cityId = $('#selectedCity').data('id'),
                    district = $('#selectedDistrict').data('name');
                    districtId = $('#selectedDistrict').data('id');

                var newCity = city ? '-'+city:'',
                    newDistrict = district ? '-'+district:'';
                if(province){
                    el.addClass('active').text(province+newCity+newDistrict).attr('m-value',province+newCity+newDistrict);
                    $('[name="'+params.districtName+'"]').val(districtId);
                    $('[name="'+params.cityName+'"]').val(cityId);
                    $('[name="'+params.provinceName+'"]').val(provinceId);
                }else{
                    el.removeClass('active').text('选择省市区/县');
                    $('[name="'+params.districtName+'"]').val('');
                    $('[name="'+params.cityName+'"]').val('');
                    $('[name="'+params.provinceName+'"]').val('');
                }
                F7.closeModal('.area-popup');
            });

            $$("#cityList").on('show',function(){
                var province = $('#selectedProvince').data('name');
                if(!province) $$(this).empty().removeClass('show');
            });

            $$("#districtList").on('show',function(){
                var city = $('#selectedCity').data('name');
                if(!city) $$(this).empty().removeClass('show');
            });
        });

    },
    getProvince:function(){
        var that = this;
        var provinceFunction = function(data){
            var list =  '<div class="list-block"><ul>';
            for (var i = 0; i < data.length; i++) {
                list += '<li>'+
                            '<label class="label-radio item-content" data-id="'+data[i].id+'" data-name="'+data[i].provinceName+'">' +
                                '<input type="radio" name="provincesRadio" value="'+data[i].id+'">' +
                                '<div class="item-inner"><div class="item-title">'+data[i].provinceName+'</div></div>' +
                            '</label>' +
                        '</li>';
            }
            list += '</ul></div>';

            $("#provinceList").html(list);
        };

        if(that.provinceData){
            provinceFunction(that.provinceData);
        }else{
            appXhr.GET(true,'/json/provinces.json').done(function(data){
                // console.log(data);
                that.provinceData = data;
                provinceFunction(that.provinceData);
                
            });
        }
        
    },
    getCity:function(id){
        var that = this;
        console.log(id);
        var cityFunction = function(data){
            var list =  '<div class="list-block"><ul>';
            for (var i = 0; i < data.length; i++) {
                list += '<li>'+
                            '<label class="label-radio item-content" data-id="'+data[i].id+'" data-name="'+data[i].name+'">' +
                                '<input type="radio" name="citiesRadio" value="'+data[i].id+'">' +
                                '<div class="item-inner"><div class="item-title">'+data[i].name+'</div></div>' +
                            '</label>' +
                        '</li>';
            }
            list += '</ul></div>';

            if(data.length > 0){
                $("#cityList").addClass('show').html(list);
            }else{
                $("#cityList").removeClass('show');
            }
            
        };

        if(that.cityData){
            cityFunction(that.cityData[id]);
        }else {
            appXhr.GET(true,'/json/cities.json').done(function(data){
                that.cityData = data;
                
                cityFunction(that.cityData[id]);
            });
        }
    },
    getDistrict:function(id){
        var that = this;

        var districtFunction = function(data){
            var list =  '<div class="list-block"><ul>';
            for (var i = 0; i < data.length; i++) {
                list += '<li>'+
                            '<label class="label-radio item-content" data-id="'+data[i].id+'" data-name="'+data[i].areaName+'">' +
                                '<input type="radio" name="districtsRadio" value="'+data[i].id+'">' +
                                '<div class="item-inner"><div class="item-title">'+data[i].areaName+'</div></div>' +
                            '</label>' +
                        '</li>';
            }
            list += '</ul></div>';

            if(data.length > 0){
                $("#districtList").addClass('show').html(list);
            }else{
                $("#districtList").removeClass('show');
            }
        };

        if(that.districtData){
            districtFunction(that.districtData[id]);
        }else {
            appXhr.GET(true,'/json/districts.json').done(function(data){
                that.districtData = data;
                
                districtFunction(that.districtData[id]);
            });
        }
    },
    selectProvince:function(params){
        var that = this;
        $("#provinceList").on('click','.label-radio',function(){
            var self = $(this),
                id = self.data('id'),
                name = self.data('name');

            F7.showTab("#cityList");
            that.getCity(id);
            $("#selectedProvince").text(name).data({
                id:id,
                name:name
            });
            $("#selectedCity").text('市').removeData();
            $("#selectedDistrict").text('区/县').removeData();
            
        });
    },
    selectCity:function(params){
        var that =  this;
        $("#cityList").on('click','.label-radio',function(){
            var self = $(this),
                id = self.data('id'),
                name = self.data('name');

            F7.showTab("#districtList");
            that.getDistrict(id);
            $("#selectedCity").text(name).data({
                id:id,
                name:name
            });
            $("#selectedDistrict").text('区/县').removeData();
        });
    },
    selecDistrict:function(params){
        var that = this;
        $("#districtList").on('click','.label-radio',function(){
            var self = $(this),
                id = self.data('id'),
                name = self.data('name');
            $("#selectedDistrict").text(name).data({
                id:id,
                name:name
            });
            
        });
    },
    formSubmit:function(){
        $("#orderForm").on('submit',function(e){
            e.preventDefault();
            var formArray = $(this).serializeArray(),formData = {};
            formArray.forEach( function(element, index) {
                formData[element.name] = element.value;
            });
            console.log(formData);
            return false;
        });

        $("#submitOrderForm").on('click',function(){
            $("#orderForm").submit();
        });
    }
};

/*F7.onPageInit('orderAddView', function(page) {
    orderEditAction.init();
});*/

module.exports = orderEditAction;
